<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="form.id ? '修改品牌' : '新增'"
    width="600"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="110"
      size="default"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="平台">
            <el-select
              v-model="form.platform_id"
              placeholder="请选择"
              class="w-full"
              @change="changePlatform"
            >
              <el-option
                v-for="item in platformOptions"
                :key="item.platform_id"
                :label="item.platform_name"
                :value="item.platform_id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="店铺">
            <el-select
              v-model="form.shop_ids"
              placeholder="请选择"
              class="w-full"
              multiple
              @change="changeStore"
            >
              <el-option
                v-for="item in shopOptions"
                :key="item.shop_id"
                :label="item.shop_name"
                :value="item.shop_id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="&nbsp" label-width="0" prop="status">
            <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="2"
              active-text="启用"
              inactive-text="禁用"
              inline-prompt
            />
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="品牌">
            <select-brand
              class="w-full"
              v-model="form.brand_ids"
              :multiple="true"
              placeholder="品牌"
            ></select-brand>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="国家">
            <SelectCountry
              class="w-full"
              v-model="form.base_trade_agent_country"
              valueKey="item"
              multiple
              placeholder="请选择国家"
            >
            </SelectCountry>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="授权代表公司" prop="importer_id">
            <SelectImporter
              v-model="form.importer_id"
              placeholder="请选择授权代表公司"
              class="w-full"
              @change="changeImporter"
            >
            </SelectImporter>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="类型" required>
            <div class="form-input">
              {{ form.base_importer?.type == 1 ? "欧代" : "英代" }}
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="电子邮件" required>
            <div class="form-input">{{ form.base_importer?.email || "" }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="联系电话" required>
            <div class="form-input">
              {{ form.base_importer?.telephone || "" }}
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="公司地址">
            <VGroup class="w-full">
              <div class="form-input overflow-hidden text-ellipsis">
                {{ form.base_importer?.province }}
              </div>
              <div class="form-input">{{ form.base_importer?.city }}</div>
              <div class="form-input">{{ form.base_importer?.area }}</div>
            </VGroup>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="详细地址" required>
            <div class="form-input form-textarea">
              {{ form.base_importer?.address || "详细地址" }}
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { createTradeAgent, editTradeAgent, getTradeAgentDetail } from "../api";
import { getShop } from "@/api/index";
import { reactive, toRefs } from "vue";
import { ElMessage } from "element-plus";
import SelectCountry from "@/components/SelectCountry";
import SelectImporter from "@/components/SelectImporter";
import useCommonStore from "@/store/modules/common";
import SelectBrand from "@/components/SelectBrand";

const commonStore = useCommonStore();
const platformOptions = computed(() => {
  if (!commonStore.platformOptions) {
    commonStore.getPlatformList();
  }
  return commonStore.platformOptions;
});

const emits = defineEmits(["query"]);
const props = defineProps({
  options: {
    type: Object,
    required: true,
  },
});

const data = reactive({
  form: {},
  visible: false,
  loading: false,
  formRef: null,
  rules: {
    platform_id: [{ required: true, message: "请选择平台", trigger: "change" }],
    importer_id: [{ required: true, message: "请选择进口商", trigger: "change" }],
  },
  shopOptions: [],
  load: false,
});

const { rules, form, visible, loading, formRef, shopOptions, load } = toRefs(data);
const open = async (id) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  if (id) await getDetail(id);
  visible.value = true;
};

const getDetail = async (id) => {
  try {
    const res = await getTradeAgentDetail({ id });
    form.value = res.data;
    changePlatform(form.value.platform_id);
  } catch (e) {
    throw Error(e);
  }
};

const changePlatform = async (val) => {
  const item = platformOptions.value.find((i) => i.platform_id == val);
  form.value.platform_name = item?.platform_name;
  try {
    const res = await getShop({
      platform_ids: [val],
    });
    form.value.store_id = "";
    shopOptions.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

// const changeStore = async (val) => {
//   const item = shopOptions.value.find((i) => i.shop_id == val);
//   form.value.store_name = item?.shop_name;
// };

const changeCountry = async (val) => {
  form.value.country_name = val;
};

const changeImporter = async (item) => {
  form.value.base_importer = item;
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      if (form.value.id) {
        editTradeAgent(form.value)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        createTradeAgent(form.value)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

const initForm = () => {
  form.value = getForm();
  shopOptions.value = [];
};

// 初始化
const getForm = () => {
  return {
    importer_id: "",
    platform_id: "",
    platform_name: "",
    store_id: null,
    store_name: [],
    site: null,
    remark: "",
    status: 1,
    country_id: "",
    country_name: "",
    base_importer: {},
  };
};

onMounted(() => {
  initForm();
});

const close = () => {
  initForm();
  visible.value = false;
};

defineExpose({ open });
</script>
<style scoped>
.form-input {
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
  background-color: var(--base-dialog-bg-color);
  box-shadow: 0 0 0 1px var(--base-border-color) inset;
  width: 100%;
  padding: 1px 10px;
}

.form-textarea {
  height: 64px;
}
</style>
